<?php

/**
 *  后台继承类
 * @file   Admin.php  
 * @date   2016-8-23 19:45:21 
 * @author Zhenxun Du<5552123@qq.com>  
 * @version    SVN:$Id:$ 
 */
namespace app\index\controller;

use think\Loader;

class Company extends Common {

    public function index() {
        $where = [];
        $name = input('name');

        if($name){
            $where['name'] = ['like',"%{$name}%"];
        }
        $lists = db('company')->field('*')
            ->where($where)
            ->order('id desc')
            ->paginate(20);



        $this->assign('lists', $lists);

        $this->assign('name', $name);
        return $this->fetch();
    }

    /*
        * 查看
        */

    public function info() {

        $id = input('id');
        if ($id) {
            //当前用户信息
            $info = db('company')->where(['id'=>$id])->find();

            $this->assign('info', $info);
        }

        return $this->fetch();
    }

    /*
     * 添加
     */

    public function add() {
        $data = input();
        if (!$data['name']) {
            $this->error('集团名称不能为空');
        }
        $row = db('company')->where(['name'=>$data['name']])->count();
        if($row>0){
            $this->error('该集团已存在');
        }
        if (!$data['label']) {
            $this->error('采样编号标识不能为空');
        }

        $addArr['name'] = $data['name'];
        $addArr['label'] = $data['label'];
        $addArr['created_at'] = time();

        $res = db('company')->insert($addArr);
        if ($res!==false) {
            $this->success('操作成功', url('index'));
        } else {
            $this->error('操作失败');
        }
    }

    /*
     * 修改
     */

    public function edit() {
        $data = input();
        if (!$data['id']) {
            $this->error('id不能为空');
        }
        if (!$data['name']) {
            $this->error('集团名称不能为空');
        }
        $row = db('company')->where(['name'=>$data['name'],'id'=>['neq',$data['id']]])->count();
        if($row>0){
            $this->error('该集团已存在');
        }
        if (!$data['label']) {
            $this->error('采样编号标识不能为空');
        }





        $addArr['name'] = $data['name'];
        $addArr['label'] = $data['label'];

        $res = db('company')->where(['id'=>$data['id']])->update($addArr);
        if ($res!==false) {
            $this->success('操作成功', url('index'));
        } else {
            $this->error('操作失败');
        }

    }

    /*
     * 删除
     */

    public function del() {
        $id = input('id');

        $res = db('company')->where(['id' => $id])->delete();
        if ($res) {
            //删除下面的所有用户
            db('user')->where(['com_id' => $id])->delete();
            $this->success('操作成功', url('index'));
        } else {
            $this->error('操作失败');
        }
    }


}
